package com.passion.web.alone;

import com.google.code.kaptcha.Producer;
import com.passion.annotation.Limit;
import com.passion.common.base.ResultVO;
import com.passion.context.MiddlewareContext;
import com.passion.frm.CaptchaCacheFrm;
import com.passion.vo.CaptchaVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.Objects;

/**
 * 类描述：验证码控制器
 *
 * @author ZhuYin
 * @since 2024年11月19日
 */
@Slf4j
@Api(tags = "验证码图片生成")
@Controller
@RequestMapping("/captcha")
public class CaptchaController {

    /** 验证码过期时间 5分钟 */
    private static final long VERIFY_CODE_EXPIRE = 5 * 60 * 1000L;

    @Resource
    private Producer producer;

    @Limit
    @ApiOperation("获取验证码信息")
    @GetMapping("/genCode")
    @ResponseBody
    public ResultVO<CaptchaVO> genCode() {
        String sessionId = Objects.requireNonNull(RequestContextHolder.getRequestAttributes()).getSessionId();
        String text = producer.createText();
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setVerifyCodeKey(sessionId);
        captchaVO.setVerifyCode(text);
        captchaVO.setExpireTime(new Date(System.currentTimeMillis() + VERIFY_CODE_EXPIRE));
        // 将验证码缓存起来备用
        MiddlewareContext.cache.put(sessionId, text, VERIFY_CODE_EXPIRE);
        return ResultVO.getSuccess(captchaVO);
    }

    @Limit
    @ApiOperation("缓存前端生成的验证码")
    @PostMapping("/cacheCode")
    @ResponseBody
    public ResultVO<Boolean> cacheCode(@RequestBody @Validated CaptchaCacheFrm frm) {
        // 将前端生成的验证码缓存起来，在登录接口验证时使用
        if (frm.getExpire() == null) {
            frm.setExpire(VERIFY_CODE_EXPIRE);
        }
        MiddlewareContext.cache.put(frm.getKey(), frm.getValue(), frm.getExpire());
        return ResultVO.getSuccess();
    }

    @Limit
    @ApiOperation("获取登录验证码图片")
    @GetMapping("/genCodeImg")
    public void genCodeImg(@ApiIgnore HttpServletResponse response) {
        String sessionId = Objects.requireNonNull(RequestContextHolder.getRequestAttributes()).getSessionId();
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        // 生成文字验证码
        String text = producer.createText();
        // 生成图片验证码
        BufferedImage image = producer.createImage(text);
        // 将验证码缓存起来备用
        MiddlewareContext.cache.put(sessionId, text, VERIFY_CODE_EXPIRE);
        try (ServletOutputStream out = response.getOutputStream()) {
            ImageIO.write(image, "jpg", out);
        } catch (Exception e) {
            log.error("向页面输出验证码图片异常", e);
        }
    }
}
